#!/bin/sh
#
# Copyright (C) Scott Walker 2007 <iswalker at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, write to:
# 	The Free Software Foundation, Inc.,
# 	51 Franklin Street, Fifth Floor
# 	Boston, MA  02110-1301, USA.
#

NAME=btpd-webui
HOMEDIR=$HOME/.btpd-webui
LOGFILE=$HOMEDIR/twistd.log
PIDFILE=$HOMEDIR/twistd.pid

# Ensure we have the twistd program
TWISTD=`which twistd`
if [ ! $TWISTD ]; then
    echo "Can't find twistd.  Do you have twisted installed?"
    exit 1
fi

# Ensure we have btpd-webui-server
BTPDWEBUI=`which btpd-webui-server`
if [ ! $BTPDWEBUI ]; then
    echo "Can't find btpd-webui-server. Is it installed and in your path?"
    exit 1
fi 

# Make the btpd-webui home directory if needed.
if [ ! -d $HOMEDIR ]; then
    mkdir --mode=770  $HOMEDIR
fi

start() {
    if [ -f $PIDFILE ]; then
        echo "$NAME is already running."      
    else
        echo -n "Starting $NAME via twistd..."
        $TWISTD --logfile=$LOGFILE --pidfile=$PIDFILE --python=$BTPDWEBUI
        sleep 1
        test -f $PIDFILE && echo "OK" || echo "Failed"
    fi
}

stop() {
    if [ ! -f $PIDFILE ]; then
        echo "$NAME is not running."
    else
        echo -n "Stopping $NAME via twistd..."
        kill `cat $PIDFILE`
        sleep 1
        test ! -f $PIDFILE && echo "OK" || echo "Failed"
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        if [ -f $PIDFILE ]; then
            echo "$NAME is running with pid `cat $PIDFILE`"
        else
            echo "$NAME is not running"
        fi
        ;;        
    *)
        echo "Usage: $NAME {start|stop|restart|status}" >&2
        exit 1;
        ;;
esac

exit 0;

